/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component} from 'react';
import { Form, Button, Badge, Select, DatePicker, Radio, Descriptions, Input, Upload, Icon, TreeSelect } from 'antd';
import {connect} from 'dva';
import moment from 'moment'
import request from '@/utils/request';

const { TextArea } = Input;
const { Option } = Select;
const TreeNode = TreeSelect.TreeNode;

const ButtonGroup = Button.Group;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fileList:[],
      all_users_reviewer:[],
      all_users_rehearer:[],
      all_departments:[],
      format:'YYYY-MM-DD'
    };
  }
  componentDidMount() {
    const that=this;
    this.fetAllUser('all_users_reviewer')
    this.fetAllUser('all_users_rehearer')
    request(`/all_departments`, {
      method: 'GET',
    }).then((response)=> {
      console.log('all_structures', response)
      if(response.status===200){
        that.setState({
          all_departments:response.data.data
        })
      }
    })
    if(this.props.editRecord){
      if(this.props.editRecord.time_granularity===1){
        this.setState({
          format:'YYYY-MM-DD'
        })
      }else{
        this.setState({
          format:'YYYY-MM-DD HH:00:00'
        })
      }
    }else{
      if(this.state.format==='YYYY-MM-DD'){
        this.props.form.setFieldsValue({
          days:moment(this.props.form.getFieldValue('end_time')).diff(
            moment(this.props.form.getFieldValue('start_time').format(this.state.format))
            ,'day')+1,
        })
      }else{
        this.props.form.setFieldsValue({
          hours:moment(this.props.form.getFieldValue('end_time')).diff(
            moment(this.props.form.getFieldValue('start_time').format(this.state.format))
            ,'hour'),
        })
      }
    }

  }
  fetAllUser=(type,value)=>{
    const that=this;
    request(`/all_staffs`, {
      method: 'GET',
      params:{
        department_id:value?value:''
      }
    }).then((response)=> {
      console.log('all_structures', response)
      if(response.status===200){
        that.setState({
          [type]:response.data.data
        })
      }
    })
  }
  renderTreeNodes = data =>
    data.map((item,index) => {

      if (item.children.length>0) {
        return (
          <TreeNode value={item.id} title={item.name} key={item.id+index} >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode  value={item.id}   key={item.id+index}  title={item.name}  />;
    });
  render() {
    const {getFieldDecorator} = this.props.form;
    const props = {
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState(({ fileList }) => ({
          fileList: [file],
        }));
        return false;
      },
      fileList: this.state.fileList,
    };
    return (
      <div>
        <Form>
          <Descriptions className={'blue-descriptions'} title={<div style={{textAlign:'center'}}>请假详情</div>} bordered>
            <Descriptions.Item label="申请人">
              {sessionStorage.getItem('username')}
            </Descriptions.Item>
            <Descriptions.Item label="请假类型">
              {getFieldDecorator('type', {
                initialValue: this.props.editRecord?this.props.editRecord.type:'事假',
              })(
                <Select >
                  <Option  value={'事假'}>{'事假'}</Option>
                  <Option  value={'病假'}>{'病假'}</Option>
                  <Option  value={'公休'}>{'公休'}</Option>
                  <Option  value={'探亲假'}>{'探亲假'}</Option>
                  <Option  value={'护理假'}>{'护理假'}</Option>
                  <Option  value={'丧假'}>{'丧假'}</Option>
                  <Option  value={'婚假'}>{'婚假'}</Option>
                </Select>
              )}
            </Descriptions.Item>

            <Descriptions.Item label="时间粒度">
              {getFieldDecorator('time_granularity', {
                initialValue: this.props.editRecord?this.props.editRecord.time_granularity:1,
              })(
                <Radio.Group onChange={(e)=>{
                  console.log(e.target.value)
                  this.setState({
                    format:e.target.value===1?'YYYY-MM-DD':'YYYY-MM-DD HH:00:00'
                  },function() {
                    console.log(this.state.format)
                    this.props.form.setFieldsValue({
                      start_time:moment(moment().format(this.state.format)),
                      end_time:moment(moment().format(this.state.format)),
                    })
                  })
                }}>
                  <Radio value={1}>天</Radio>
                  <Radio value={2}>小时</Radio>
                </Radio.Group>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="开始时间" >
              {getFieldDecorator('start_time', {
                initialValue: this.props.editRecord?moment(this.props.editRecord.start_time):moment(),
              })(
                <DatePicker onChange={(date, dateString)=>{
                  console.log(moment(dateString).diff(
                    moment(this.props.form.getFieldValue('end_time').format(this.state.format))
                    ,'day'))
                  if(this.state.format==='YYYY-MM-DD'){
                    this.props.form.setFieldsValue({
                      days:moment(this.props.form.getFieldValue('end_time').format(this.state.format)).diff(
                        moment(dateString)
                        ,'day')+1,
                    })
                  }else{
                    this.props.form.setFieldsValue({
                      hours:moment(this.props.form.getFieldValue('end_time').format(this.state.format)).diff(
                        moment(dateString)
                        ,'hour'),
                    })
                  }
                }} style={{width:'150px'}} allowClear={false}  showTime={{ format: 'HH:00:00' }} format={this.state.format}/>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="结束时间" >
              {getFieldDecorator('end_time', {
                initialValue:  this.props.editRecord?moment(this.props.editRecord.end_time):moment(),
              })(
                <DatePicker onChange={(date, dateString)=>{
                  console.log(moment(dateString).diff(
                    moment(this.props.form.getFieldValue('start_time').format(this.state.format))
                    ,'day'))
                  if(this.state.format==='YYYY-MM-DD'){
                    this.props.form.setFieldsValue({
                      days:moment(dateString).diff(
                        moment(this.props.form.getFieldValue('start_time').format(this.state.format))
                        ,'day')+1,
                    })
                  }else{
                    this.props.form.setFieldsValue({
                      hours:moment(dateString).diff(
                        moment(this.props.form.getFieldValue('start_time').format(this.state.format))
                        ,'hour'),
                    })
                  }
                }} style={{width:'150px'}} allowClear={false}  showTime={{ format: 'HH:00:00' }} format={this.state.format}/>
              )}
            </Descriptions.Item>
            {
              this.state.format==='YYYY-MM-DD'?<Descriptions.Item label="请假时长(天)" >
                {getFieldDecorator('days', {
                  initialValue: this.props.editRecord?this.props.editRecord.days:'',
                })(
                  <Input />
                )}
              </Descriptions.Item>:<Descriptions.Item label="请假时长(时)" >
                {getFieldDecorator('hours', {
                  initialValue: this.props.editRecord?this.props.editRecord.hours:'',
                })(
                  <Input />
                )}
              </Descriptions.Item>
            }

            <Descriptions.Item label="请假事由" span={3}>
              {getFieldDecorator('cause', {
                initialValue:this.props.editRecord?this.props.editRecord.cause:'',
              })(
                <TextArea rows={3}/>
              )}

            </Descriptions.Item>
            <Descriptions.Item label="上传附件" span={3}>
              {getFieldDecorator('file', {
                rules: [{required: true, message: '固件文件不能为空'}],
              })(
                <Upload.Dragger {...props}>
                  <p className="ant-upload-text" style={{fontSize:'14px'}}> <Icon type="inbox" />点击选择文件</p>
                </Upload.Dragger>
              )}

            </Descriptions.Item>
            <Descriptions.Item label="审批部门">
                <TreeSelect
                  treeDefaultExpandAll
                  allowClear
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  onChange={(value)=>{
                      this.fetAllUser('all_users_reviewer',value)
                  }}
                >
                  {this.renderTreeNodes(this.state.all_departments)}
                </TreeSelect>
            </Descriptions.Item>
            <Descriptions.Item label="审批人" span={2}>
              {getFieldDecorator('reviewer_id', {
                initialValue: this.props.editRecord?this.props.editRecord.reviewer_id:'',
              })(
                <Select >
                  {
                    this.state.all_users_reviewer.map((item,index)=>{
                      return <Option key={index} value={item.id}>
                        {item.name}
                      </Option>
                    })
                  }
                </Select>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="复审部门">
              <TreeSelect
                treeDefaultExpandAll
                allowClear
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                onChange={(value)=>{
                  this.fetAllUser('all_users_rehearer',value)
                }}
              >
                {this.renderTreeNodes(this.state.all_departments)}
              </TreeSelect>
            </Descriptions.Item>
            <Descriptions.Item label="复审人" span={2}>
              {getFieldDecorator('rehearer_id', {
                initialValue: this.props.editRecord?this.props.editRecord.rehearer_id:'',
              })(
                <Select >
                  {
                    this.state.all_users_rehearer.map((item,index)=>{
                      return <Option key={index} value={item.id}>
                        {item.name}
                      </Option>
                    })
                  }
                </Select>
              )}
            </Descriptions.Item>
          </Descriptions>
        </Form>

      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


